import React, { useState, useEffect, useRef } from "react";
import {
  ActivityIndicator,
  FlatList,
  TouchableOpacity,
  View,
  Text,
  Animated,
} from "react-native";
import { Avatar } from "@rneui/themed";
import { Ionicons } from "@expo/vector-icons";
import { useTheme } from "@/contexts/ThemeContext";
import { router } from "expo-router";
import styles from "./index.style";

// 假设我们会有这样的hook来管理群聊数据
// 实际实现时需要替换为真实的数据源
const useGroupChatState = () => {
  // 模拟数据，实际项目中应该从API或store获取
  const [groups, setGroups] = useState([
    {
      id: "1",
      name: "项目开发群",
      avatar: "https://via.placeholder.com/50",
      memberCount: 8,
      lastMessage: "下午3点开会讨论进度",
      lastMessageTime: new Date().getTime() - 1000 * 60 * 30, // 30分钟前
    },
    {
      id: "2",
      name: "家人群",
      avatar: "https://via.placeholder.com/50",
      memberCount: 5,
      lastMessage: "晚上回家吃饭",
      lastMessageTime: new Date().getTime() - 1000 * 60 * 60, // 1小时前
    },
    {
      id: "3",
      name: "同学会",
      avatar: "https://via.placeholder.com/50",
      memberCount: 20,
      lastMessage: "周末聚会，不见不散",
      lastMessageTime: new Date().getTime() - 1000 * 60 * 60 * 3, // 3小时前
    },
  ]);

  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);

  const fetchGroups = async () => {
    // 实际项目中应该从API获取数据
    setLoading(true);
    try {
      // 模拟API请求
      await new Promise((resolve) => setTimeout(resolve, 500));
      // setGroups(response.data) 实际获取数据后更新
      setLoading(false);
    } catch (err) {
      setError(err);
      setLoading(false);
    }
  };

  return { groups, loading, error, fetchGroups };
};

export default function GroupChatList() {
  const { colors } = useTheme();
  const { groups, loading, error, fetchGroups } = useGroupChatState();
  const [isExpanded, setIsExpanded] = useState(true);
  const [localLoading, setLocalLoading] = useState(false);
  const [hasAttemptedLoad, setHasAttemptedLoad] = useState(false);
  const rotateAnimation = useRef(new Animated.Value(0)).current;

  // 加载数据
  const loadData = async (forceReload = false) => {
    if (!forceReload && groups && groups.length > 0) {
      setLocalLoading(false);
      setHasAttemptedLoad(true);
      return;
    }

    try {
      setLocalLoading(true);
      await fetchGroups();
    } finally {
      setLocalLoading(false);
      setHasAttemptedLoad(true);
    }
  };

  // 组件挂载时加载数据
  useEffect(() => {
    loadData();
  }, []);

  // 处理展开/折叠动画
  useEffect(() => {
    Animated.timing(rotateAnimation, {
      toValue: isExpanded ? 1 : 0,
      duration: 200,
      useNativeDriver: true,
    }).start();
  }, [isExpanded]);

  const rotateInterpolate = rotateAnimation.interpolate({
    inputRange: [0, 1],
    outputRange: ["0deg", "90deg"],
  });

  // 切换展开/折叠状态
  const toggleExpand = () => {
    setIsExpanded(!isExpanded);
  };

  // 渲染头部（带折叠按钮）
  const renderHeader = () => (
    <TouchableOpacity
      style={[
        styles.headerContainer,
        { backgroundColor: colors.backgroundLight },
      ]}
      onPress={toggleExpand}
      activeOpacity={0.7}
    >
      <View style={styles.headerTitleContainer}>
        <Text style={[styles.headerTitle, { color: colors.text.primary }]}>
          我的群聊
        </Text>
        <Text style={[styles.headerCount, { color: colors.text.secondary }]}>
          {groups.length}
        </Text>
      </View>
      <Animated.View
        style={{
          transform: [{ rotate: rotateInterpolate }],
        }}
      >
        <Ionicons
          name="chevron-forward"
          size={20}
          color={colors.text.secondary}
        />
      </Animated.View>
    </TouchableOpacity>
  );

  // 如果正在加载且没有数据，显示加载指示器
  if ((loading || localLoading) && (!groups || groups.length === 0)) {
    return (
      <View>
        {renderHeader()}
        <View style={styles.loading}>
          <ActivityIndicator size="small" />
        </View>
      </View>
    );
  }

  // 渲染列表
  return (
    <View>
      {renderHeader()}

      {isExpanded && (
        <FlatList
          data={groups}
          keyExtractor={(item) => item.id}
          renderItem={({ item }) => {
            const { name, avatar, memberCount } = item;
            return (
              <TouchableOpacity
                onPress={() => {
                  // 这里应该导航到群聊页面
                  router.navigate("/groupchat/detail");
                }}
                style={[
                  styles.listItem,
                  {
                    borderBottomColor: colors.border.divider,
                  },
                ]}
              >
                <View style={styles.avatarWrapper}>
                  <Avatar
                    rounded
                    size={50}
                    source={{ uri: avatar }}
                    containerStyle={styles.avatar}
                  />
                </View>
                <View
                  style={[
                    styles.infoContainer,
                    { backgroundColor: colors.card.background },
                  ]}
                >
                  <Text
                    style={[styles.nickname, { color: colors.text.primary }]}
                  >
                    {name}
                  </Text>
                  <Text
                    style={[
                      styles.memberCount,
                      { color: colors.text.secondary },
                    ]}
                  >
                    {memberCount} 位成员
                  </Text>
                </View>
              </TouchableOpacity>
            );
          }}
          ListEmptyComponent={
            <View style={styles.emptyContainer}>
              <Text
                style={[styles.emptyText, { color: colors.text.secondary }]}
              >
                暂无群聊
              </Text>
            </View>
          }
        />
      )}
    </View>
  );
}
